<?php
namespace app\common\third;

class Excel
{

    /**
     * 使用phpoffice/phpspreadsheet导出excel,支持xlsx格式
     * @param array $data 导出数据
     * @param array $header 表头
     * @param string $fileName 文件名
     * @param string $sheetName sheet名
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    static public function exportExcel(array $data, array $header, string $fileName = '', string $sheetName = 'sheet1')
    {
        $fileName = $fileName ?: date('YmdHis', time());
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle($sheetName);
        $sheet->fromArray($header, null, 'A1');
        $sheet->fromArray($data, null, 'A2');
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save($fileName . '.xlsx');
        // 直接输出文件
        header('Content-Type: application/vnd.ms-excel'); // 响应头没看到这个类型
        
        header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx"');
        header('Cache-Control: max-age=0');
        
        return $writer->save('php://output');
    }

}